@echo off
title Star Resonance Damage Counter - Launcher

:: Add error handling and logging
setlocal enabledelayedexpansion

:: Record startup time
echo [%time%] Startup script execution started > start_log.txt

:: Change to script directory
cd /d "%~dp0"
echo [%time%] Changed to script directory: %CD% >> start_log.txt

echo ========================================
echo    Star Resonance Damage Counter    
echo           Project Launcher           
echo ========================================
echo If startup fails, check start_log.txt file
echo ========================================
echo.

echo [CHECK] Verifying administrator privileges...
echo [%time%] Checking administrator privileges >> start_log.txt
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo [WARNING] Administrator privileges not detected
    echo [%time%] WARNING: Administrator privileges not detected >> start_log.txt
    echo [INFO] Some operations may require admin rights
    echo [INFO] If startup fails, try running as administrator
    echo.
) else (
    echo [SUCCESS] Administrator privileges verified
    echo [%time%] Administrator privileges verified successfully >> start_log.txt
)
echo.

echo [CHECK] Verifying project files...
echo [INFO] Script location: %~dp0
echo [INFO] Current directory: %CD%
echo [%time%] Checking project files, current directory: %CD% >> start_log.txt
echo [CHECK] Looking for server.js...

if not exist "server.js" (
    echo [ERROR] server.js file not found!
    echo [%time%] ERROR: server.js file does not exist >> start_log.txt
    echo [CHECK] JavaScript files in current directory:
    dir /b *.js 2>>start_log.txt
    echo [CHECK] All files in current directory:
    dir /b 2>>start_log.txt
    echo.
    echo [SOLUTION] Please ensure this script runs in the project root directory
    echo [SOLUTION] Directory should contain: server.js, package.json, etc.
    echo [SOLUTION] Or copy this script to the correct project directory
    echo.
    goto error_exit
)
echo [SUCCESS] Found server.js file
echo [%time%] server.js file verification successful >> start_log.txt

if not exist "package.json" (
    echo [ERROR] package.json file not found!
    echo [%time%] ERROR: package.json file not found >> start_log.txt
    echo [SOLUTION] Please ensure you run this script in the project root directory
    echo [INFO] Current directory: %CD%
    echo.
    goto error_exit
)

if not exist "node_modules" (
    echo [ERROR] node_modules directory not found!
    echo [%time%] ERROR: node_modules directory not found >> start_log.txt
    echo [SOLUTION] Please run install.bat first to install dependencies
    echo [INFO] Current directory: %CD%
    echo [INFO] Contents of current directory:
    dir /b
    echo.
    goto error_exit
)
echo [OK] Project files verification passed
echo.

echo [CHECK] Verifying Node.js...
node --version >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERROR] Node.js not detected!
    echo [%time%] ERROR: Node.js not detected >> start_log.txt
    echo [SOLUTION] Please run install.bat first to setup environment
    echo.
    goto error_exit
)
for /f "tokens=*" %%i in ('node --version') do set NODE_VERSION=%%i
echo [OK] Node.js version: %NODE_VERSION%
echo.

echo [CHECK] Checking port 8989...
netstat -an | find "8989" >nul 2>&1
if %errorLevel% equ 0 (
    echo [WARNING] Port 8989 is already in use
    echo [AUTO] Automatically terminating occupying processes...
    for /f "tokens=5" %%i in ('netstat -ano ^| find "8989" ^| find "LISTENING"') do (
        echo [TERMINATE] Terminating process PID: %%i
        taskkill /PID %%i /F >nul 2>&1
    )
    echo [INFO] Waiting for port to be released...
    timeout /t 2 >nul 2>&1
)
echo [OK] Port check completed
echo.

echo ========================================
echo         Starting Project...         
echo ========================================
echo.
echo [START] Starting server...
echo [TIP] Project will run in background, browser will open automatically
echo [TIP] Closing this window will stop the server
echo.

set START_TIME=%time%

echo [START] Launching server with automatic configuration...
echo [INFO] Auto-selecting network device 3 and log level info...
echo [INFO] Server output will be logged to server.log

if not exist "server_input.txt" (
    echo [INFO] Creating automatic input file...
    echo 3> server_input.txt
    echo info>> server_input.txt
)

echo [START] Starting Node.js server...
echo [DEBUG] Input will be: device 3, log level info
echo [DEBUG] Killing any existing node processes...
taskkill /f /im node.exe >nul 2>&1

echo [DEBUG] Starting server with Node.js wrapper...
start /b cmd /c "node server_wrapper.js" >server.log 2>&1

echo [WAIT] Waiting for server startup...
echo [INFO] Giving server 15 seconds to fully initialize...

:: Wait for server to start - simplified approach
timeout /t 15 >nul 2>&1

echo [DEBUG] Checking if server started successfully...
type server.log 2>nul | find "Web Server started" >nul 2>&1
if %errorLevel% equ 0 (
    echo [DEBUG] Server startup confirmed in log!
) else (
    echo [DEBUG] Checking port status directly...
    netstat -an | find ":8989" >nul 2>&1
    if %errorLevel% equ 0 (
        echo [DEBUG] Port 8989 is listening!
    ) else (
        echo [WARNING] Server may not have started properly
        echo [DEBUG] Current server.log content:
        echo ================== SERVER LOG ==================
        type server.log 2>nul
        echo ============== END SERVER LOG ================
    )
)

echo [OK] Server started successfully!
echo.

echo [START] Opening browser...
echo [INFO] Server should be ready at: http://localhost:8989

:: Simple and direct browser launch - only one method
echo [LAUNCH] Opening browser to http://localhost:8989
start http://localhost:8989

echo.
echo [SUCCESS] Browser launch completed!
echo [INFO] Please visit: http://localhost:8989
echo [INFO] If browser didn't open, copy the URL above
echo.

echo ========================================
echo      Project Started Successfully!      
echo ========================================
echo.
echo Access URL: http://localhost:8989
echo Start Time: %START_TIME%
echo Project Dir: %CD%
echo Log File: server.log
echo.
echo Usage Instructions:
echo   1. Ensure game is started and connected to server
echo   2. Select network device in web interface
echo   3. Start playing to see damage statistics
echo.
echo Operation Tips:
echo   - Press Ctrl+C to stop server
echo   - Closing this window will also stop server
echo   - To restart, run this script again
echo.
echo ========================================
echo.

:monitor
echo [MONITOR] Server running... (Press Ctrl+C to stop)
timeout /t 10 >nul 2>&1

netstat -an | find "8989" | find "LISTENING" >nul 2>&1
if %errorLevel% neq 0 (
    echo.
    echo [ERROR] Server stopped unexpectedly!
    echo [TIP] Please check server.log file for error details
    echo.
    echo Press any key to exit...
    pause >nul
    exit /b 1
)

goto monitor

:cleanup
echo.
echo [CLEANUP] Stopping server...
for /f "tokens=5" %%i in ('netstat -ano ^| find "8989" ^| find "LISTENING"') do (
    taskkill /PID %%i /F >nul 2>&1
)
echo [DONE] Server stopped
echo.
echo Thank you for using Star Resonance Damage Counter!
exit /b 0

:: Error handling function (placed at end to avoid execution)
:error_exit
echo.
echo [ERROR] An error occurred during startup!
echo [INFO] Error details have been logged to start_log.txt
echo [TIPS] Please check the following common issues:
echo   1. Run as administrator
echo   2. Have you run install.bat to setup environment
echo   3. Is Node.js correctly installed
echo   4. Is port 8989 occupied by other programs
echo.
echo Press any key to view detailed logs...
pause >nul
if exist start_log.txt (
    echo ========== STARTUP LOG ==========
    type start_log.txt
    echo ========== END OF LOG ==========
)
if exist server.log (
    echo ========== SERVER LOG ==========
    type server.log
    echo ========== END OF LOG ==========
)
echo.
echo Press any key to exit...
pause >nul
exit /b 1